package com.lgc.netdemo.config

import okhttp3.Cookie
import okhttp3.CookieJar
import okhttp3.HttpUrl

/**
 * 用于持久化的cookieJar实现类
 */
internal class LocalCookieJar : CookieJar
{
    //cookie的本地化存储
    private val cache= mutableListOf<Cookie>()
    override fun loadForRequest(url: HttpUrl): List<Cookie> {
        //过期的cookie
        val invalidCookie:MutableList<Cookie> = mutableListOf()
        //有效的cookie
        val validCookie:MutableList<Cookie> = mutableListOf()
        for (cookie in cache){
            if(cookie.expiresAt<System.currentTimeMillis()){
                //判断是否过期
                invalidCookie.add(cookie)
            }else{
                //匹配Cookie对应的url
                validCookie.add(cookie)
            }
        }
        //缓存中移除过期的cookie
        cache.removeAll(invalidCookie)

        //返回有效的cookie
        return validCookie
    }

    /**
     * 将cookie保存到本地
     */
    override fun saveFromResponse(url: HttpUrl, cookies: List<Cookie>) {
       cache.addAll(cookies)
    }
}